package com.wolfking.jeesite.config;

import com.wolfking.jeesite.exception.SignException;
import freemarker.template.TemplateModelException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import java.io.IOException;

@Slf4j
//@Component
public class SsoRootFilter implements Filter {

    @Autowired
    private SsoConfig ssoConfig;

//    @Autowired
//    private freemarker.template.Configuration configuration;

    @Override
    public void doFilter(ServletRequest request, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            String selfRootUrlByRequest = ssoConfig.getSelfRootUrlByRequest();
            log.info("current selfRootUrl is {}", selfRootUrlByRequest);
//            configuration.setSharedVariable("rootUrl", selfRootUrlByRequest);
            filterChain.doFilter(request, servletResponse);
        } catch (Exception e) {
            if (e.getCause() != null && e.getCause() instanceof SignException) {
                log.warn("SignException");
            } else if (e instanceof TemplateModelException) {
                log.warn("TemplateModelException");
            } else if (e instanceof SignException) {
                log.warn("SignException");
            } else if (e instanceof IOException) {
                throw (IOException) e;
            } else if (e instanceof ServletException) {
                log.warn("", e);
                throw (ServletException) e;
            } else {
                log.warn("", e);
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}
